#!/usr/bin/python3
import os.path

import requests
import json
import argparse

def worst_of(l1, l2):
    map_status = {'P':0, 'X':1, 'W':2, 'F':3}

    if map_status[l1[0]] < map_status[l2[0]]:
        return l2
    else:
        return l1

def get_piuparts_summary(archs, components, suite):
    result = {"_comment": "",
              "_date": "",
              "_id": "",
              "_type": "",
              "_version": "",
              "packages": {} }

    for arch in archs:
        for component in components:
            url_json = f"http://10.42.201.11/piuparts/{arch}-{suite}-{component}/summary.json"
            try:
                data = requests.get(url=url_json).json()
            except requests.exceptions.JSONDecodeError as e:
                print(f"{arch} no component : {component}")
                continue

            except requests.exceptions.ConnectionError as e:
                raise Exception("检查piuparts主机网络是否连通")

            for key in data.keys():
                if key != "packages":
                    result[key] = data[key]

            for package_name in data['packages']:
                if package_name not in result['packages']:
                    result['packages'][package_name] = data['packages'][package_name]
                else:
                    result['packages'][package_name][suite] = worst_of(result['packages'][package_name][suite], data['packages'][package_name][suite])
    return result

if __name__ == "__main__":

    archs = ['amd64', 'arm64', 'loong64', 'loongarch64', 'armhf', 'sw64']
    components = ['main', 'universe', 'restricted', 'multiverse']
    # suite = 'v11-2603-preview'
    parser = argparse.ArgumentParser(description="获取piuparts的所有结果，并合并到一个文件中")
    parser.add_argument("suite", help="要获取的系列")
    parser.add_argument("--dir", "-d", help="存储到的文件夹路径")
    args = parser.parse_args()
    suite = args.suite


    data = get_piuparts_summary(archs, components, suite)
    file_name = f"piuparts-summary-{suite}.json"
    if args.dir:
        file_name = os.path.join(args.dir, file_name)
    with open(file_name, 'w') as f:
        json.dump(data, f, indent=4)
    print(f"out to file {file_name}")
